const { executeQuery } = require('../config/dbConfig');
const { generateToken } = require('../utils/jwt');
const { generateAvatarSVG } = require('../utils/avatar');

class UserService {
  // 获取用户列表
  async getUserList() {
    const users = await executeQuery(
      'SELECT id, username, nickname, avatar_type, avatar_data, status, created_at FROM users'
    );
    return users;
  }

  // 用户注册
  async register(userData) {
    // 检查用户名是否已存在
    const existingUser = await executeQuery(
      'SELECT id FROM users WHERE username = ?',
      [userData.username]
    );

    if (existingUser.length > 0) {
      throw new Error('用户名已存在');
    }

    // 生成默认头像
    const avatarData = generateAvatarSVG(userData.nickname);

    const result = await executeQuery(
      `INSERT INTO users (username, password, nickname, avatar_type, avatar_data) 
       VALUES (?, ?, ?, 'default', ?)`,
      [userData.username, userData.password, userData.nickname, avatarData]
    );

    return result.insertId;
  }

  // 用户登录
  async login(username, password, remember = false) {
    // 查找用户
    const [user] = await executeQuery(
      'SELECT * FROM users WHERE username = ? AND password = ?',
      [username, password]
    );

    if (!user) {
      throw new Error('用户名或密码错误');
    }

    // 检查用户状态
    if (user.status === 0) {
      throw new Error('该账号已被冻结');
    }

    // 生成token
    const token = generateToken({
      id: user.id,
      username: user.username,
      role: 'user'
    }, remember);

    // 返回用户信息和token
    return {
      token,
      user
    };
  }

  // 获取用户信息
  async getUserById(id) {
    const result = await executeQuery(
      'SELECT id, username, nickname, avatar_type, avatar_data, status, created_at FROM users WHERE id = ?',
      [id]
    );

    return result[0];
  }

  // 更新用户信息
  async updateUser(id, userData) {


    const updateFields = [];
    const updateValues = [];

    if (userData.nickname) {
      updateFields.push('nickname = ?');
      updateValues.push(userData.nickname);
    }
    if (userData.avatar_data) {
      updateFields.push('avatar_type = ?, avatar_data = ?');
      updateValues.push('custom', userData.avatar_data);
    }

    if (updateFields.length === 0) {
      throw new Error('没有要更新的字段');
    }

    updateValues.push(id);

    await executeQuery(
      `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );

    return true;
  }

  // 更新密码
  async updatePassword(userId, oldPassword, newPassword) {
    // 验证原密码是否正确
    const user = await executeQuery(
      'SELECT password FROM users WHERE id = ?',
      [userId]
    );
    
    if (!user.length || user[0].password !== oldPassword) {
      const error = new Error('原密码不正确');
      error.status = 400;
      throw error;
    }
    
    // 更新密码
    const result = await executeQuery(
      'UPDATE users SET password = ? WHERE id = ?',
      [newPassword, userId]
    );

    if (result.affectedRows === 0) {
      const error = new Error('密码更新失败');
      error.status = 500;
      throw error;
    }

    return true;
  }

  // 获取用户的书籍
  async getUserBooks(userId) {

    const books = await executeQuery(
      `SELECT p.*, u.nickname as author_name,
       (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as likes_count,
       (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comments_count,
       (SELECT AVG(score) FROM ratings WHERE post_id = p.id) as avg_rating
       FROM posts p
       LEFT JOIN users u ON p.user_id = u.id
       WHERE p.user_id = ? AND p.status = 1
       ORDER BY p.created_at DESC`,
      [userId]
    );

    return books;
  }

  // 获取用户的评论
  async getUserComments(userId) {

    const comments = await executeQuery(
      `SELECT c.*, p.title as post_title, u.nickname as user_name
       FROM comments c
       LEFT JOIN posts p ON c.post_id = p.id
       LEFT JOIN users u ON c.user_id = u.id
       WHERE c.user_id = ?
       ORDER BY c.created_at DESC`,
      [userId]
    );

    return comments;
  }
}

module.exports = new UserService(); 